<script setup lang="ts">
  import { findIndex, random } from 'lodash'
  /**
   * 游戏说明
   * 1、大满贯
   * 2、送彩金
   * 3、风火轮(中120倍)
   * 4、三元(中随机三个灯)
   * 5、对对碰(送对角两颗灯) 
   * 6、超级变变变(5-20倍)
   * 7、天龙八部(中随机八个灯)
   * 8、纵横四海(送对角四颗灯)
   * 9、九莲宝灯(中随机九个灯)
   * 10、小猫变身(中50、100、120倍)
   * 11、一射双调：先送一个颜色(中8倍)，再送另一个颜色
   * 比倍送明牌(5-9倍)
   */
  enum ClickAction {
    Left,
    Right,
    Single,
    Double,
    Large,
    Small,
    Start,
    Color,
    Score
  }

 const ellipse = ref(null)

 const circles = ref(null)

 useGameLayout({
  ellipse,
  circles
 })

 const gameLoop = ref(false)

 const color = ref('red')

 const wins = ref(0)

 const total = ref(9999)

 const history = ref(0)

 const multiple = ref(0)

 const circleItems = ref([
  {
    name: '小铃铛',
    label: 'bell',
    type: 'small',
    color: ''
  },
  {
    name: '大铃铛',
    label: 'bell',
    type: 'normal',
    color: ''
  },
  /**
  * 小三元 大铃铛 大芒果 大橘子
  * 大三元 大西瓜 大双星 大七七
  */
  {
    name: '三元',
    label: 'triple',
    type: 'normal',
    color: ''
  },
  {
    name: '小双星',
    label: 'star',
    type: 'small'
  },
  {
    name: '大双星',
    label: 'star',
    type: 'normal',
    color: ''
  },
  /**
  * 当前分数押注x5-20
  */
  {
    name: '超级变变变',
    label: 'super',
    type: 'normal',
    color: ''
  },
  {
    name: '小芒果',
    label: 'mango',
    type: 'small',
    color: ''
  },
  {
    name: '大芒果',
    label: 'mango',
    type: 'normal',
    color: ''
  },
  /**
  * 选一个小灯x50、x100、x120
  */
  {
    name: '小猫变身',
    label: 'cat',
    type: 'normal',
    color: ''
  },
  {
    name: '小双七',
    label: '77',
    type: 'small',
    color: ''
  },
  {
    name: '大双七',
    label: '77',
    type: 'normal',
    color: ''
  },
  /**
  * 随机奖
  * 送说明1-10其中一个
  */
  {
    name: '随机奖',
    label: 'random',
    type: 'normal',
    color: ''
  },
  {
    name: '小橘子',
    label: 'orange',
    type: 'small',
    color: ''
  },
  {
    name: '大橘子',
    label: 'orange',
    type: 'normal',
    color: ''
  },
  /**
  * 所有灯中一遍
  */
  {
    name: '大满贯',
    label: 'all',
    type: 'normal',
    color: ''
  },
  {
    name: '苹果',
    label: 'apple',
    type: 'normal',
    color: ''
  },
  {
    name: '大bar',
    label: 'king',
    type: 'normal',
    barType: 100,
    color: ''
  },
  {
    name: '达人',
    label: 'person',
    type: 'normal',
    color: ''
  },
  {
    name: '小bar',
    label: 'king',
    type: 'normal',
    barType: 50,
    color: ''
  },
  {
    name: '苹果',
    label: 'apple',
    type: 'normal',
    color: ''
  },
  /**
  * 连续八个灯
  */
  {
    label: 'long',
    type: 'normal',
    color: ''
  },
  {
    name: '小西瓜',
    label: 'watermelon',
    type: 'small',
    color: ''
  },
  {
    name: '大西瓜',
    label: 'watermelon',
    type: 'normal',
    color: ''
  },
  // 随机奖 同上
  {
    name: '随机奖',
    label: 'random',
    type: 'normal',
    color: ''
  }
 ])

 const colors = ref([
  {
    label: '红',
    value: ''
  },
  {
    label: '红',
    value: ''
  },
  {
    label: '黄',
    value: ''
  },
  {
    label: '黄',
    value: ''
  },
  {
    label: '绿',
    value: ''
  },
  {
    label: '绿',
    value: ''
  }
 ])
 
 const pColor = ref(0)
 const sPointer = ref(0)
 const restColors = () => {
  colors.value.forEach((c) => {
    c.value = ''
  })
  circleItems.value.forEach((c) => {
    c.color = ''
  })
 }

 const resultColors = useArr(14)

 const buttons = ref([
  {
    label: '←',
    action: ClickAction.Left
  },
  {
    label: '→',
    action: ClickAction.Right
  },
  {
    label: '单',
    action: ClickAction.Single
  },
  {
    label: '双',
    action: ClickAction.Double
  },
  {
    label: '大',
    action: ClickAction.Large
  },
  {
    label: '小',
    action: ClickAction.Small
  },
  {
    label: '启动',
    action: ClickAction.Start
  }
 ])

 const coloredButtons = ref([
    // x10
    {
      color: 'red',
      value: 0,
      label: '红',
      action: ClickAction.Color
    },
    // x10、x15、x20、x25
    {
      color: 'yellow',
      value: 0,
      label: '黄',
      action: ClickAction.Color
    },
    // x10
    {
      color: 'green',
      value: 0,
      label: '绿',
      action: ClickAction.Color
    }
 ])

 const specialButtons = ref([
    // 大x10 小x20
    {
      label: '达人',
      value: 0,
      img: 'person',
      action: ClickAction.Score
    },
    // 大x10 小x20
    {
      label: 'BAR',
      value: 0,
      img: 'king',
      action: ClickAction.Score
    },
    // 大x10 小x20
    {
      label: '双七',
      value: 0,
      img: '77',
      action: ClickAction.Score
    },
    // 大x10 小x20
    {
      label: '双星',
      value: 0,
      img: 'star',
      action: ClickAction.Score
    },
    // 大x10 小x20
    {
      label: '西瓜',
      value: 0,
      img: 'watermelon',
      action: ClickAction.Score
    },
    // 大x10 小x20
    {
      label: '铃铛',
      value: 0,
      img: 'bell',
      action: ClickAction.Score
    },
    // 大x10 小x20
    {
      label: '芒果',
      value: 0,
      img: 'mango',
      action: ClickAction.Score
    },
    // 大x10 小x20
    {
      label: '橘子',
      value: 0,
      img: 'orange',
      action: ClickAction.Score
    },
    // x5
    {
      label: '苹果',
      value: 0,
      img: 'apple',
      action: ClickAction.Score
    }
 ])

 const _findIndex = (ref, label): number => {
  return findIndex(ref.value, { label })
 }

 const toLeft = () => { 
  const add = wins.value * 2 || 1
  if (total.value - add >= 0) {
    wins.value += add
    total.value -= add
  }
 }

 const toRight = () => {
  if (wins.value > 0) {
    total.value += wins.value
    wins.value = 0
  }
 }

 const getGameColor = () => {
  const colors = ['red', 'green', 'yellow']
  const weights = [47.5, 47.5, 5]
  const totalWeight = weights.reduce((acc, val) => acc + val, 0)
  let randomNum = Math.random() * totalWeight
  let selectedColor
  for (let i = 0; i < colors.length; i++) {
    if (randomNum <= weights[i]) {
      selectedColor = colors[i]
      break
    }
    randomNum -= weights[i]
  }
  return selectedColor
 }

 const updateColorHistroy = () => {
  resultColors.value.unshift(color.value)
  if (resultColors.value.length > 14) {
    resultColors.value.pop()
  }
 }

 const timer1 = useIntervalFn(() => {
  history.value = random(10000, 999999)
 }, 1000)

 const timer2 = useIntervalFn(() => {
  multiple.value = random(1, 99)
 }, 1000)

 const timer3 = useIntervalFn(() => {
  const colorsMap = [
    ['red', 'red'],
    ['yellow', 'yellow'],
    ['green', 'green']
  ]
  colors.value.forEach((c) => {
    c.value = ''
  })
  const currentColors = colorsMap[pColor.value]
  colors.value[2 * pColor.value].value = currentColors[0]
  colors.value[2 * pColor.value + 1].value = currentColors[1]
  pColor.value = (pColor.value + 1) % colorsMap.length
}, 300)

  const blink = (callback) => {
    const index = sPointer.value
    const times = 3
    let blinkCount = 0
    const { pause, resume } = useIntervalFn(() => {
      if (blinkCount % 2 == 0) {
        circleItems.value[index].color = color.value
      } else {
        circleItems.value[index].color = ''
      }
      blinkCount++
      if (blinkCount >= times * 2) {
        circleItems.value[index].color = ''
        pause()
        callback && callback()
      }
    }, 300)
    resume()
  }

  const runMarquee = () => {
    let step = 0, lap = 0;
    let currentIndex = sPointer.value - 1
    const marqueeCount = 3
    const size = circleItems.value.length
    const rest = random(0, size)
    const { pause, resume } = useIntervalFn(() => {
      circleItems.value.forEach((item, index) => {
        if (index >= currentIndex && index < currentIndex + marqueeCount) {
          item.color = ''
        }
      })
      currentIndex = (currentIndex + 1) % size
      for (let i = 0; i < marqueeCount; i++) {
        const index = (currentIndex + i) % size
        circleItems.value[index].color = color.value
      }
      sPointer.value = currentIndex
      step++
      lap = (step - rest) / size
      if (lap > 3) {
        circleItems.value.forEach(c => {
          c.color = ''
        })
        pause()
        blink(() => {
          stopGame()
        })
      }
    }, 30)
    resume()
  }

 timer2.pause()
 timer3.pause()

 const stopGame = () => {
  restColors()
  pColor.value = 0
  timer1.pause()
  timer2.resume()
  timer3.pause()
  gameLoop.value = false
  circleItems.value[sPointer.value].color = color.value
 }

 const startGame = () => {
  gameLoop.value = true
  history.value = random(1, 160)
  color.value = getGameColor()
  updateColorHistroy()
  blink(() => {
    runMarquee()
  })
 }

 const setSingle = (params) => {
  // TODO
 }

 const setDouble = (params) => {
  // TODO
 }

 const setSmall = (params) => {
    // TODO
 }

 const setLarge = (params) => {
    // TODO
 }

 const setColor = ({ label }) => {
  const index = _findIndex(coloredButtons, label)
  if (index !== -1 && total.value >= 10) {
    const value = coloredButtons.value[index].value
    if (value < 1000) {
      total.value = total.value - 10
      coloredButtons.value[index].value = value + 10
    }
  }
 }

 const setScore = ({ label }) => {
  const index = _findIndex(specialButtons, label)
  if (index !== -1 && total.value >= 1) {
    const value = specialButtons.value[index].value 
    if (value < 300) {
      total.value = total.value - 1
      specialButtons.value[index].value = value + 1
    }
  }
 }

 const allZero = () => {
  const allZeroColor = coloredButtons.value.every(button => button.value === 0)
  const allZeroScore = specialButtons.value.every(button => button.value === 0)
  return allZeroColor && allZeroScore
 }

 const checked_1 = computed(() => allZero() && wins.value !== 0)

 const checked_2 = computed(() => allZero())

 const clickHandler = (params) => {
    if (gameLoop.value) return
    switch (params.action) {
      case ClickAction.Left:
        if (checked_2.value) {
          toLeft()
        }
        break
      case ClickAction.Right:
        if (checked_2.value) {
          toRight()
        }
        break
      case ClickAction.Single:
        if (checked_1.value) {
          setSingle(params)
        }
        break
      case ClickAction.Double:
        if (checked_1.value) {
          setDouble(params)
        }
        break
      case ClickAction.Small:
        if (checked_1.value) {
          setSmall(params)
        }
        break
      case ClickAction.Large:
        if (checked_1.value) {
          setLarge(params)
        }
        break
      case ClickAction.Color:
        if (wins.value === 0) {
          setColor(params)
        }
        break
      case ClickAction.Score:
        if (wins.value === 0) {
          setScore(params)
        }
        break
      case ClickAction.Start:
        startGame()
    }
 }
</script>

<template>
  <div class="wrapper">
    <div id="game">
      <div class="ellipse" ref="ellipse">
        <div class="score">
          <!--赢的分数-->
          <div class="wins" v-number="[6, wins]"></div>
          <!--剩余的分数-->
          <div class="total" v-number="[6, total]"></div>
        </div>
        <!--跑马灯-->
        <div :class="'circle bg-' + item.color" ref="circles" v-for="item in circleItems" :key="item">
          <img :class="item.type === 'small' && 'small'"  :src="`/imgs/${item.label}.png`" :alt="item.name" />
        </div>
        <!--0-14-->
        <div class="hp hp-history">
          <span v-number="[6, history]"></span>
        </div>
        <!--比大小-->
        <div class="hp hp-multiple">
          <span v-number="[2, multiple]"></span>
        </div>
        <!--颜色跑灯-->
        <div class="color">
          <div :class="'color-circle bg-' + color.value" v-for="color in colors" :key="color">{{ color.label }}</div>
        </div>
        <!--操作区域-->
        <div class="bottom">
          <!--颜色跑灯历史记录-->
          <div class="result">
            <div class="result-circle" :class="'bg-' + color" v-for="(color, index) in resultColors" :key="index"></div>
          </div>
          <!--基础操作-->
          <div class="buttons">
            <div class="item" v-for="button in buttons" :key="button.label">
              <button @click="clickHandler(button)">{{ button.label }}</button>
            </div>
          </div>
          <!--颜色操作-->
          <div class="buttons">
            <div class="item" v-for="button in coloredButtons" :key="button.color">
              <span v-number="[4, button.value]"></span>
              <button @click="clickHandler(button)" :class="'bg-' + button.color" >{{ button.label }}</button>
            </div>
          </div>
          <!--点子操作-->
          <div class="buttons">
            <div class="item" v-for="button in specialButtons" :key="button.label">
              <span v-number="[3, button.value]"></span>
              <button @click="clickHandler(button)">
                <img :src="`/imgs/${button.img}.png`" />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>